﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GenericHtml
{
    public class TableBuilder
    {
        public DynamicTable Table { get; private set; }

        public List<DynamicColumn> Columns { get; private set; }

        public TableBuilder(DynamicTable table)
        {
            this.Table = table;
            this.Columns = new List<DynamicColumn>();
        }

        public void AddColumn(DynamicColumn column)
        {
            this.Columns.Add(column);
        }

        public string GetSql()
        {
            StringBuilder builder = new StringBuilder();

            builder.AppendFormat("CREATE TABLE {0}(", Table.Name);
            builder.Append(Environment.NewLine);

            builder.AppendFormat("\tId int identity primary key,\n");
            builder.AppendFormat("\tCreateUser int not null,\n");
            builder.AppendFormat("\tUpdateUser int not null,\n");
            builder.AppendFormat("\tCreationTime datetime not null default GETDATE(),\n");
            builder.AppendFormat("\tUpdatedTime datetime not null default GETDATE()\n");

            if (Columns.Count > 0)
            {
                builder.AppendFormat(", {0}", GetAttribute(Columns[0]));
                for (int i = 1; i < Columns.Count; i++)
                {
                    builder.AppendFormat(", {0}\n", GetAttribute(Columns[i]));
                }
            }

            builder.Append(");");
            return builder.ToString();
        }

        public static string Required(bool required)
        {
            return required ? "NOT NULL" : "NULL";
        }

        private static string GetAttribute(DynamicColumn column)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(column.Name);
            builder.Append(' ');
            switch (column.TypeId)
            {
                case ColumnType.DICTIONARY:
                case ColumnType.ID:
                    builder.AppendFormat("int {0}", Required(column.Required));
                    break;

                case ColumnType.DECIMAL:
                    builder.AppendFormat("decimal(18, {0}) {1}", column.Precision, Required(column.Required));
                    break;

                case ColumnType.DATETIME:
                case ColumnType.DATE:
                case ColumnType.TIME:
                    builder.AppendFormat("datetime {0}", Required(column.Required));
                    break;

                case ColumnType.STRING:
                    builder.AppendFormat("nvarchar({0}) {1}", column.MaxLength, Required(column.Required));
                    break;
            }

            return builder.ToString();
        }
    }
}
